<template>
  <div class="article-edit">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑文章' : '新增文章' }}</h2>
    </div>
    
    <el-form ref="articleForm" :model="articleForm" :rules="rules" label-width="100px" v-loading="loading">
      <!-- 标题 -->
      <el-form-item label="标题" prop="title">
        <el-input v-model="articleForm.title" placeholder="请输入文章标题"></el-input>
      </el-form-item>
      
      <!-- 分类 -->
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="articleForm.categoryId" placeholder="请选择文章分类" popper-append-to-body>
          <el-option
            v-for="item in categoryOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      
      <!-- 封面图片 -->
      <el-form-item label="封面图片" prop="coverImageUrl">
        <el-upload
          class="cover-uploader"
          action="/api/admin/file/upload"
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeFileUpload">
          <img v-if="articleForm.coverImageUrl" :src="articleForm.coverImageUrl" class="cover-image">
          <i v-else class="el-icon-plus cover-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      
      <!-- 内容（富文本编辑器） -->
      <el-form-item label="内容" prop="content">
        <div id="editor-toolbar"></div>
        <div id="editor-text" style="border:1px solid #d9d9d9; min-height:200px;"></div>
      </el-form-item>
      
      <!-- 文章状态 -->
      <el-form-item label="状态">
        <el-radio-group v-model="articleForm.status">
          <el-radio :label="0">草稿</el-radio>
          <el-radio :label="1">发布</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <!-- 表单操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('articleForm')">保存</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';
import E from 'wangeditor';

export default {
  name: 'ArticleEdit',
  data() {
    return {
      isEdit: false,
      loading: false,
      articleId: null,
      articleForm: {
        id: null,
        title: '',
        content: '',
        categoryId: null,
        coverImageUrl: '',
        status: 0 // 默认草稿
      },
      rules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择文章分类', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      categoryOptions: [],
      editor: null
    };
  },
  created() {
    // 获取分类数据
    this.fetchCategoryOptions();
    // 判断是否为编辑模式
    const id = this.$route.params.id;
    if (id) {
      this.isEdit = true;
      this.articleId = id;
      this.fetchArticleDetail(id);
    }
  },
  mounted() {
    // 初始化wangEditor
    this.editor = new E('#editor-toolbar', '#editor-text');
    this.editor.config.onchange = (html) => {
      this.articleForm.content = html;
    };
    
    // 设置编辑器z-index较低，避免遮挡下拉菜单
    this.editor.config.zIndex = 100;
    
    // 配置图片上传
    this.editor.config.uploadImgServer = '/api/admin/file/upload';
    this.editor.config.uploadFileName = 'file';
    this.editor.config.uploadImgHooks = {
      customInsert: (insertImg, result) => {
        if (result.code === 200) {
          insertImg(result.data); // result.data为图片完整URL
        } else {
          this.$message.error(result.msg || '图片上传失败');
        }
      }
    };
    
    // 配置视频上传
    this.editor.config.uploadVideoServer = '/api/admin/file/upload';
    this.editor.config.uploadVideoName = 'file';
    this.editor.config.uploadVideoAccept = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'];
    this.editor.config.uploadVideoMaxSize = 1024 * 1024 * 50; // 50MB，与后端配置一致
    
    // 视频上传钩子函数
    this.editor.config.uploadVideoHooks = {
      // 视频上传并返回了结果，视频插入已成功
      customInsert: (insertVideo, result) => {
        if (result.code === 200) {
          // 直接插入视频URL，让编辑器处理视频标签的生成
          insertVideo(result.data);
        } else {
          this.$message.error(result.msg || '视频上传失败');
        }
      },
      // 视频上传错误
      // eslint-disable-next-line no-unused-vars 
      error: (xhr, editor) => {
        this.$message.error('视频上传发生错误');
      },
      // 视频上传超时
      // eslint-disable-next-line no-unused-vars
      timeout: (xhr, editor) => {
        this.$message.error('视频上传超时');
      }
    };
    
    // 创建编辑器
    this.editor.create();
    
    // 如果是编辑，回显内容
    if (this.articleForm.content) {
      this.editor.txt.html(this.articleForm.content);
    }
  },
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy();
      this.editor = null;
    }
  },
  methods: {
    // 获取文章详情
    fetchArticleDetail(id) {
      this.loading = true;
      axios.get(`/api/admin/article/${id}`)
        .then(response => {
          if (response.data.code === 200) {
            const articleDetail = response.data.data;
            this.articleForm = {
              id: articleDetail.id,
              title: articleDetail.title,
              content: articleDetail.content,
              categoryId: articleDetail.categoryId,
              coverImageUrl: articleDetail.coverImageUrl,
              status: articleDetail.status
            };
            // 回显富文本内容
            if (this.editor && this.articleForm.content) {
              this.editor.txt.html(this.articleForm.content);
            }
          } else {
            this.$message.error(response.data.msg || '获取文章详情失败');
          }
        })
        .catch(error => {
          console.error('获取文章详情错误', error);
          this.$message.error('获取文章详情失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取分类选项
    fetchCategoryOptions() {
      axios.get('/api/admin/article/category', {
        params: { enabled: true }
      }).then(response => {
        if (response.data.code === 200) {
          this.categoryOptions = response.data.data;
        } else {
          this.$message.error(response.data.msg || '获取分类数据失败');
        }
      }).catch(error => {
        console.error('获取分类数据错误', error);
        this.$message.error('获取分类数据失败');
      });
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const articleData = {
            ...this.articleForm
          };
          const method = this.isEdit ? 'put' : 'post';
          const url = this.isEdit ? `/api/admin/article/${this.articleId}` : '/api/admin/article';
          const successMsg = this.isEdit ? '文章更新成功' : '文章保存成功';
          axios[method](url, articleData)
            .then(response => {
              if (response.data.code === 200) {
                this.$message.success(successMsg);
                this.goBack();
              } else {
                this.$message.error(response.data.msg || '操作失败');
              }
            })
            .catch(error => {
              console.error('保存文章错误', error);
              this.$message.error('保存文章失败');
            });
        } else {
          return false;
        }
      });
    },
    // 上传前验证文件
    beforeFileUpload(file) {
      const isImage = file.type.indexOf('image/') !== -1;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$message.error('上传的文件必须是图片!');
      }
      if (!isLt2M) {
        this.$message.error('上传的图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
    // 上传封面成功
    handleCoverSuccess(res, file) {
      if (res.code === 200) {
        this.articleForm.coverImageUrl = res.data;
        if (file.url && file.url.startsWith('blob:')) {
          URL.revokeObjectURL(file.url);
        }
      } else {
        this.$message.error(res.msg || '上传失败');
      }
    },
    // 返回列表
    goBack() {
      this.$router.push('/dashboard/article-management');
    }
  }
};
</script>

<style>
/* 全局样式，确保下拉菜单显示在富文本编辑器之上 */
.el-select-dropdown {
  z-index: 3000 !important;
}
</style>

<style scoped>
.article-edit {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader:hover {
  border-color: #409EFF;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.cover-image {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 